package top.chaileilei.zookeeper.javaapi;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @Description
 * @Time 2019/1/23
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class JavaApiDemo1 implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);


    public static void main(String[] args) throws Exception {
        simple2();
    }

    /**
     * @Description 创建zookeeper会话
     * @Param
     * @Return void
     * @Author CHAILEILEI
     * @Time 2019/1/23
     * @Blogs www.chaileilei.top
     */
    public static void simple1() throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("119.27.189.174:2181", 5000, new JavaApiDemo1());
        System.out.println(zooKeeper.getState());
        countDownLatch.await();
    }

    /**
     * @Description 创建一个复用sessionId和seesionPassword的zookeeper对象实例
     * @Param
     * @Return void
     * @Author CHAILEILEI
     * @Time 2019/1/23
     * @Blogs www.chaileilei.top
     */
    public static void simple2() throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("119.27.189.174:2181", 5000, new JavaApiDemo1());
        countDownLatch.await();
        long sessionId = zooKeeper.getSessionId();
        byte[] sessionPasswd = zooKeeper.getSessionPasswd();
        zooKeeper = new ZooKeeper("119.27.189.174:2181", 5000, new JavaApiDemo1(), sessionId, "dd".getBytes());
        zooKeeper = new ZooKeeper("119.27.189.174:2181", 5000, new JavaApiDemo1(), sessionId, sessionPasswd);
        Thread.sleep(3000033);
    }




    @Override
    public void process(WatchedEvent event) {
        System.out.println("receive watched event:" + event);
        if (Event.KeeperState.SyncConnected == event.getState()) {
            countDownLatch.countDown();
        }
    }
}
